package com.stlm2.controller;

import com.stlm2.core.common.page.PageView;
import com.stlm2.dems.entity.*;
import com.stlm2.dems.service.*;
import com.stlm2.util.IntegerUtil;
import com.stlm2.util.codecontent.CodeContent;
import com.sun.tools.javac.jvm.Code;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author：fuchunyu
 * Date：2017/12/20
 * Description：
 */
@Controller
@RequestMapping("integralOrder")
public class IntegralOrderController {

    @Resource
    private UserService userService;
    @Resource
    private IntegralGoodsService integralGoodsService;
    @Resource
    private AddressService addressService;
    @Resource
    private IntegralOrderService integralOrderService;
    @Resource
    private PeriodsService periodsService;



    /**
     *
     * @param token  用户标识
     * @param goodsId  商品ID
     * @param num 商品数量
     * @param addressId 地址ID
     * @return  创建订单
     */
    @ResponseBody
    @RequestMapping(value = "/submitOrder.json", produces = "application/json;charset=utf-8")
    public String submitOrder(String companyCode,String token,Integer goodsId,Integer num,Integer addressId,Integer periodsId){
        User user=userService.getByToken(token);
        if(user==null)
            return CodeContent.returnLogin();
        IntegralGoods integralGoods=integralGoodsService.findEntityById(goodsId);
        if(integralGoods==null)
            return CodeContent.returnFailure("没有找到商品！");
        if(num==null||num.intValue()<0)
            return CodeContent.returnFailure("请检查商品数量!");
        Address address=addressService.findEntityById(addressId);
        if(address==null)
            return CodeContent.returnFailure("请添加地址！");
        if(integralGoods.getGoods_type().equals(GoodsType.IntegralPrize)){
            if(!IntegerUtil.isNotNull(periodsId))
                return CodeContent.returnFailure("请检查购买期号！");
        }

        IntegralOrder integralOrder=integralOrderService.createOrder(integralGoods,address,num,user,periodsId);
        if(integralOrder!=null)
            return CodeContent.returnSuccess(integralOrder.getCode());
        return CodeContent.returnFailure("订单提交失败！");
    }

    /**
     * @param page  页数
     * @param token  用户标识
     * @param orderStateValue   订单状态（1.创建订单3.支付订单，5发货订单10,确认收货6已完成2.取消订单）
     * @param goodsTypeValue 订单类型（1.兑换订单，2.抽奖订单）
     * @return  订单列表
     */
    @ResponseBody
    @RequestMapping(value = "/searchOrder.json", produces = "application/json;charset=utf-8")
    public String searchOrder(String companyCode, ModelMap model, String page, String token, Integer orderStateValue,Integer goodsTypeValue,Integer prizeStateValue ){
        int pageNo = 1;
        int pageSize = 20;
        if (NumberUtils.isDigits(page) && !"0".equals(page.trim())) {
            pageNo = NumberUtils.toInt(page);
        }

        User user=userService.getByToken(token);
        if(user==null)
            return CodeContent.returnLogin();
        if(!IntegerUtil.isNotNull(goodsTypeValue))
            return CodeContent.returnFailure("商品类型为空！");
        IntegralOrder integralOrder=new IntegralOrder();
        if(IntegerUtil.isNotNull(orderStateValue))
            integralOrder.setOrderStateValue(orderStateValue);
        integralOrder.setUserId(user.getId());
        integralOrder.setGoodsTypeValue(goodsTypeValue);
        if(prizeStateValue!=null)
            integralOrder.setPrizeState(BooleanUtils.toBoolean(prizeStateValue));

        PageView pageview = integralOrderService.getPage(pageNo, pageSize, integralOrder);
        if (pageview != null) {
            model.put("datas", integralOrderService.convertModel(pageview.getRecords()));
            model.put("recordsTotal", pageview.getRowCount());
            model.put("totalPage", pageview.getPageCount());
            model.put("pageNow", pageview.getPageNow());
            model.put("code",1);
            model.put("msg","success");
        }
        return  new JSONObject(model).toString();

    }


    /**
     * @param token  用户标识
     * @param orderId   订单ID
     * @return  取消订单
     */
    @ResponseBody
    @RequestMapping(value = "/cancelOrder.json", produces = "application/json;charset=utf-8")
    public String cancelOrder(String companyCode,String token,Integer orderId){
        User user=userService.getByToken(token);
        if (user==null)
            return CodeContent.returnLogin();
        if(!IntegerUtil.isNotNull(orderId))
            return CodeContent.returnFailure("订单错误！");
        IntegralOrder params=new IntegralOrder();
        params.setUserId(user.getId());
        params.setId(orderId);

        List<IntegralOrder> integralOrderList=integralOrderService.getList(-1,-1,params);
        IntegralOrder integralOrder=integralOrderList.get(0);
        if(integralOrder==null)
            return CodeContent.returnFailure("没有找到订单！");
        if(!integralOrder.getOrderState().equals(OrderState.Create))
            return CodeContent.returnFailure("不是创建订单，无法取消！");
        integralOrder.setOrderStateValue(2);
        integralOrder.setCancelTime(new Date());
        integralOrderService.updateEntity(integralOrder);
        return CodeContent.returnSuccess(null);
    }

    /**
     * @param token  用户标识
     * @param orderId   订单ID
     * @return  确认收货
     */
    @ResponseBody
    @RequestMapping(value = "/receiptOrder.json", produces = "application/json;charset=utf-8")
    public String receiptOrder(String companyCode,String token,Integer orderId){
        User user=userService.getByToken(token);
        if (user==null)
            return CodeContent.returnLogin();
        if(!IntegerUtil.isNotNull(orderId))
            return CodeContent.returnFailure("订单错误！");
        IntegralOrder params=new IntegralOrder();
        params.setUserId(user.getId());
        params.setId(orderId);

        List<IntegralOrder> integralOrderList=integralOrderService.getList(-1,-1,params);
        IntegralOrder integralOrder=integralOrderList.get(0);
        if(integralOrder==null)
            return CodeContent.returnFailure("没有找到订单！");
        if(!integralOrder.getOrderState().equals(OrderState.Deliveried))
            return CodeContent.returnFailure("不是已发货订单，无法确认收货！");
        integralOrder.setOrderStateValue(6);
        integralOrder.setReceiptEndTime(new Date());
        integralOrderService.updateEntity(integralOrder);
        return CodeContent.returnSuccess(null);
    }

    /*
   * sfy
   * 2017年10月24日09:33:10
   * 立即购买，生成一个预售单
   * params type orderInfor "[{},{}]"
   * */
    @ResponseBody
    @RequestMapping(value = "/buyRightNow.json", produces = "application/json;charset=UTF-8")
    public String buyRightNow(String companyCode,String token, Integer goodsId,BigDecimal num,ModelMap map,Integer periodis) {


        User user = userService.getByToken(token);
        if (user == null)
            return CodeContent.returnLogin();
    /*
        * 处理用户收货地址问题
        * */
        //用户是否已经设置收货地址
        Address userAddress = addressService.getByUserId(user.getId());
        if (userAddress == null) {
            map.put("addressType", 1);
            map.put("addressContent", "请填写您的收货地址");
        } else {
        /*
        *地址参数精简
        * */
            Map<String, Object> addressMap = new HashMap<String, Object>();
            addressMap = addressService.buildModel(userAddress);
            map.put("address", addressMap);
            map.put("addressType", 2);
        }
        if(periodis!=null&&periodis>0){
            Periods periods=periodsService.findEntityById(periodis);
            goodsId=periods.getGoodsId();
        }

        IntegralGoods integralGoods=integralGoodsService.findEntityById(goodsId);
        if(integralGoods==null)
            return CodeContent.returnFailure("没有找到商品");
        ModelMap goodsMap=new ModelMap();
        goodsMap.put("goodName",integralGoods.getName());
        goodsMap.put("goodsPrice",integralGoods.getUnitIntegral());
        goodsMap.put("imgUrl",integralGoods.getMainImg());
        goodsMap.put("num",num);
        map.put("goods",goodsMap);
        BigDecimal allPrice=integralGoods.getUnitIntegral().multiply(num);
        /*
        * 合计金钱
        * */
        map.put("allPrice", allPrice);
        map.put("endPrice", allPrice);


        return new JSONObject(map).toString();

    }
}
